package com.tianhui.consignortwofei.mvp.ui.activity;

import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.fgs.common.CommonPresenter;
import com.fgs.common.CommonResponse;
import com.fgs.common.CommonView;
import com.fgs.common.pictureSelector.GlideEngine;
import com.fgs.common.progress.ExceptionHandle;
import com.fgs.common.progress.ObserverResponseListener;

import com.fgs.common.utils.DateUtil;
import com.fgs.common.widget.SelectDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.base.BaseActivity;
import com.tianhui.consignortwofei.base.BaseFragment;
import com.tianhui.consignortwofei.manager.SharedPreferenceManager;
import com.tianhui.consignortwofei.mvp.model.DriverModel;
import com.tianhui.consignortwofei.mvp.model.GoodsModel;
import com.tianhui.consignortwofei.mvp.model.enty.DictionaryInfo;
import com.xuexiang.xui.widget.picker.widget.TimePickerView;
import com.xuexiang.xui.widget.picker.widget.builder.TimePickerBuilder;
import com.xuexiang.xui.widget.picker.widget.listener.OnTimeSelectListener;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author fgs
 * @date 2020/4/28
 * @description
 **/
public class BaoJiaWebActivity extends BaseActivity {

//    @BindView(R.id.activity_about_appNameTextView)
//    TextView mAppNameTextView;
//    @BindView(R.id.activity_about_appVersionTextView)
//    TextView mAppVersionTextView;
//    @BindView(R.id.activity_about_updateLinearLayout)
//    LinearLayout mUpdateLinearLayout;
//    UpdateContext updateContext;


    @BindView(R.id.layout_search_kufang)
    TextView layout_search_kufang;
    @BindView(R.id.layout_search_huoquan)
    EditText layout_search_huoquan;

    @BindView(R.id.layout_search_editText)
    AutoCompleteTextView searchEditText;

    @BindView(R.id.wb_text)
    WebView wb_text;

    @BindView(R.id.iv_image)
    ImageView iv_image;

    @BindView(R.id.ll_bg)
    LinearLayout ll_bg;




    private DriverModel driverModel;
    private boolean fangXiang=true;//true 竖向 false 横向

    @Override
    public int getLayoutId() {
        return R.layout.activity_baojia_web;
    }

    @Override
    public CommonPresenter createPresenter() {
        return null;
    }

    @Override
    public CommonView createView() {
        return null;
    }

    @Override
    public void init() {
        setTitle("报价列表");
//        setSubTitle("旋转");

        driverModel=new DriverModel();
        mModel = new GoodsModel();

//        String content = detail.getContent();
//        content = content.replace("<img", "<img style=max-width:100%;height:auto");
//        wb_text.loadDataWithBaseURL( null, content , "text/html", "UTF-8", null ) ;
        searchEditText.setHint("请输入报价人");

        wb_text.getSettings().setSupportZoom(true); // 允许缩放
        wb_text.getSettings().setBuiltInZoomControls(true);
        wb_text.getSettings().setDisplayZoomControls(false);// 显示缩放工具栏
        wb_text.getSettings().setJavaScriptEnabled(true);
        wb_text.addJavascriptInterface(new WebAppInterface(this,iv_image), "android");


        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
            wb_text.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        wb_text.getSettings().setBlockNetworkImage(false);





        requestDriverList("",true,1);
    }

    @Override
    public BaseFragment createFragment() {
        return null;
    }

//    @OnClick(R.id.activity_about_versionUpdateSettingItemView)
//    public void versionUpdate() {
//        updateCheck();
//    }

    @Override
    public void onSubtitleClick() {
//        fangXiang=!fangXiang;
//        //旋转
//        if (fangXiang){
//            //竖屏设置
//            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//        }else {
//            //横屏设置
//            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//        }

    }

    @OnClick(R.id.layout_search_textView)
    public void searchDriverDetail() {

        String mSearchKey = searchEditText.getText().toString();
        requestDriverList(mSearchKey,true,1);
    }


    @OnClick(R.id.tv_chongzhi)
    public void chongzhi() {
        searchEditText.setText("");
        layout_search_huoquan.setText("");
        layout_search_kufang.setText("");

    }

    @OnClick(R.id.iv_image)
    public void imageClose() {
        iv_image.setVisibility(View.GONE);

    }

    //货权选择
    private SelectDialog mCargoRightsSelectDialog;
    @OnClick(R.id.layout_search_huoquan)
    public void selectHuoQuan() {
        selectTime();
//        if (mCargoRightsSelectDialog == null) {
//            requestCargoRights();
//        } else {
//            mCargoRightsSelectDialog.show();
//        }
    }

    private GoodsModel mModel;
    //货权列表
    private void requestCargoRights() {
        if (null==mModel) {
            mModel = new GoodsModel();
        }
        Map<String, String> map = new HashMap<>();
        map.put("pid", "2795");
        mModel.dictionaryModel(getContext(), map, true, bindLifecycle(), new ObserverResponseListener<CommonResponse<List<DictionaryInfo>>>() {
            @Override
            public void onNext(CommonResponse<List<DictionaryInfo>> commonResponse) {

                if (commonResponse.getCode() == 20000) {
                    List<DictionaryInfo> dictionaryInfoList = commonResponse.getData();
                    if (dictionaryInfoList != null && dictionaryInfoList.size() > 0) {
//                            showCargoRightsList(dictionaryInfoList);
                        showCargoRightsDialog(dictionaryInfoList);
                    }
                }

            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                setMsg(e.message);
            }
        });
    }


    private void showCargoRightsDialog(List<DictionaryInfo> dictionaryInfoList) {
        mCargoRightsSelectDialog = new SelectDialog<DictionaryInfo>(this);
        mCargoRightsSelectDialog.setTitle("请选择货权");
        mCargoRightsSelectDialog.setList(dictionaryInfoList);
        mCargoRightsSelectDialog.show();

        mCargoRightsSelectDialog.setOnSelectItemClickLister(new SelectDialog.OnSelectItemClickListener<DictionaryInfo>() {
            @Override
            public void onItemClick(DictionaryInfo iSelectViewItem, int position) {
                layout_search_huoquan.setText(iSelectViewItem.getSelectItemText());
//                mGoodsInfo.customerno = iSelectViewItem.getSelectItemTextValue();
//                clearSelectDispatcher();
//                requestDispatcherList();
//                LogUtil.print("SelectedCargoRight", iSelectViewItem.getSelectItemText() + "----" + iSelectViewItem.getSelectItemTextValue());
            }
        });
    }


    //类别选择
    private SelectDialog mLeiBieSelectDialog;
    @OnClick(R.id.layout_search_kufang)
    public void selectLeiBie() {

        //货权选择
//        if (mLeiBieSelectDialog == null) {
//            requestCargoRightsLeiBie();
//        } else {
//            mLeiBieSelectDialog.show();
//        }
    }

    private void requestCargoRightsLeiBie() {
        if (null==mModel) {
            mModel = new GoodsModel();
        }
        Map<String, String> map = new HashMap<>();
        map.put("pid", "11");
        mModel.dictionaryModel(getContext(), map, true, bindLifecycle(), new ObserverResponseListener<CommonResponse<List<DictionaryInfo>>>() {
            @Override
            public void onNext(CommonResponse<List<DictionaryInfo>> commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    List<DictionaryInfo> dictionaryInfoList = commonResponse.getData();
                    if (dictionaryInfoList != null && dictionaryInfoList.size() > 0) {
//                            showCargoRightsList(dictionaryInfoList);
                        showCargoRightsDialogLeiBie(dictionaryInfoList);
                    }
                }

            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                setMsg(e.message);
            }
        });
    }



    private void showCargoRightsDialogLeiBie(List<DictionaryInfo> dictionaryInfoList) {
        mLeiBieSelectDialog = new SelectDialog<DictionaryInfo>(this);
        mLeiBieSelectDialog.setTitle("请选择货权");
        mLeiBieSelectDialog.setList(dictionaryInfoList);
        mLeiBieSelectDialog.show();

        mLeiBieSelectDialog.setOnSelectItemClickLister(new SelectDialog.OnSelectItemClickListener<DictionaryInfo>() {
            @Override
            public void onItemClick(DictionaryInfo iSelectViewItem, int position) {
                layout_search_kufang.setText(iSelectViewItem.getSelectItemText());
//                mGoodsInfo.customerno = iSelectViewItem.getSelectItemTextValue();
//                clearSelectDispatcher();
//                requestDispatcherList();
//                LogUtil.print("SelectedCargoRight", iSelectViewItem.getSelectItemText() + "----" + iSelectViewItem.getSelectItemTextValue());
            }
        });
    }


    public void requestDriverList(String paihao, boolean isDialog,int page) {
        String huoquan = layout_search_huoquan.getText().toString();
        String kufang = layout_search_kufang.getText().toString();

//        Map<String, String> map = new HashMap<>();
////        map.put("page", page+"");
////        map.put("limit", "15");
////        map.put("order", "desc");
////        map.put("sort", "create_time");
//
//        map.put("name", paihao);//牌号
////        map.put("warehouse", kufang);//库房
//        map.put("ownership", huoquan);//货权
//        map.put("nametype", kufang);//类别11  name="+paihao

        String token = SharedPreferenceManager.getInstance().getToken();
        String content="https://cnor.haojuntong.com/customer/plastics/quotation/getReportListApp?ownership="
        +"&startDate="+huoquan+"&endDate="+huoquan+"&username="+paihao+"&nametype="+kufang+"&token="+token;

//        String content="http://192.168.5.60:8084/plastics/quotation/getReportListApp?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MTA3NzI3ODQsInVzZXJJZCI6OTUyOCwidXVpZCI6ImFhNzY4M2EwLWU1N2UtNDQ4ZC05YTZiLTg3MzNmNWYyZGQ0YyIsInVzZXJuYW1lIjoiaGpfd2FuZ3RlbmcifQ.P9p2KC4qa1kKgfFbqOucmePMO-IxXh8OZDYq3d8o90U";
        wb_text.loadUrl(content);
//          wb_text.loadUrl("https://www.baidu.com");
//        wb_text.loadDataWithBaseURL( null, content , "text/html", "UTF-8", null ) ;


//        if (2==lookType){
//
//
//
//            map.put("username", paihao);
//            map.put("status", "1");
//        }
//        driverModel.getBaoJiaWeb(this, map, isDialog, bindLifecycle(), new ObserverResponseListener<CommonResponse>() {
//            @Override
//            public void onNext(CommonResponse commonResponse) {
//                if (!isFinishing() && !isDestroyed()) {
//                    if (commonResponse.getCode() == 20000) {
//                        String content = commonResponse.getData().toString();
//                        wb_text.loadDataWithBaseURL( null, content , "text/html", "UTF-8", null ) ;
//
//                    } else {
//                        showToast(commonResponse.getMsg());
//                    }
//                }
//            }
//
//
//            @Override
//            public void onError(ExceptionHandle.ResponseThrowable e) {
//                showToast(e.message);
//            }
//        });
    }

    public class WebAppInterface {
        Context mContext;
        ImageView image;

        WebAppInterface(Context c,ImageView iv_image) {
            mContext = c;
            image=iv_image;
        }

        @JavascriptInterface
        public void callMobile(String toast) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                    image.setVisibility(View.VISIBLE);
////            ImageLoader.init().loadImageWithUrl(image, toast, false);
//                    Glide.with(mContext)
//                            .load(toast)
//                            .into(image);

                    List<LocalMedia> selectList =new ArrayList<>();
                    LocalMedia media=new LocalMedia();
                    media.setFileName("internet");
                    media.setPath(toast);
//                    media.setCutPath(quotationListDTO.getPicture());
                    selectList.add(media);
                    // 预览图片 可自定长按保存路径
                    PictureSelector.create(BaoJiaWebActivity.this)
                            .themeStyle(com.fgs.common.R.style.picture_default_style) // xml设置主题
                            .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 设置相册Activity方向，不设置默认使用系统
                            .isNotPreviewDownload(true)// 预览图片长按是否可以下载
                            .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                            .openExternalPreview(0, selectList);

                }
            });


//            GlideEngine.createGlideEngine().loadImage(BaoJiaWebActivity.this,toast,iv_image);

        }
    }


    private TimePickerView endTimePickerView;
    private void selectTime() {
        if (null == endTimePickerView) {
            endTimePickerView = new TimePickerBuilder(this, new OnTimeSelectListener() {
                @Override
                public void onTimeSelected(Date date, View v) {
                    String string = DateUtil.getStandardTime(date.getTime(), "yyyy-MM-dd");
                    layout_search_huoquan.setText(string);

                }
            })
                    .setTitleText("选择日期")
                    .build();
            endTimePickerView.show();
        }

        endTimePickerView.show();
    }


}
